﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using QianBuo.Lottery.Web.Models;
using Code.Commen;
using Code.Models;
using System.Web.Routing;
using System.IO;
using System.Text;
using QianBuo.Lottery.Web.Models.Scheme;

namespace QianBuo.Lottery.Web.Controllers
{
    public class SchemeController : BaseController
    {
        SchemeManage SM;
        public SchemeController()
        {
        }
        //
        // GET: /Scheme/
        #region 方案列表
        public ActionResult Index(DefaultModel model)
        {
            if (model == null)
                model = new DefaultModel();
            if (model.LotteryIDs == null || model.LotteryIDs.Count() == 0)
                model.LotteryIDs = CacheManage.Lottery.OrderBy(p=>p.Value.ID).OrderBy(p=>p.Value.Sort).Select(p => new SelectListItem { Selected = model.where == null ? false : model.where.LotteryID == p.Value.ID, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            if (model.WinModels == null || model.WinModels.Count() == 0)
                model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Selected = model.where == null ? false : model.where.WinModelID == p.Value.ID, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            if (model.ConsumptionRatios == null || model.ConsumptionRatios.Count() == 0)
                model.ConsumptionRatios = CacheManage.Ratio.Select(p => new SelectListItem{Selected=model.where==null?false:model.where.ConsumptionRatio==p.Value.Ratio,Text=p.Value.Name,Value=p.Value.Ratio.ToString()});

            var where = getWhere(model);
            int sumCount;
            if (model.pageInfo == null)
            {
                model.pageInfo = new PageInfo();
                model.pageInfo.CurrPage = 1;
            }
            var data = new SchemeManage().SchemeList(LoginUserID,(model.pageInfo.CurrPage - 1) * model.pageInfo.PageCount,model.pageInfo.PageCount,out sumCount, where.Propertie1, where.Propertie2).ToList();

            model.pageInfo.SunCount = sumCount;
            model.SchemeDetail = data.ToArray();

            if(model.where==null)
                model.where = new DefaultModel.Where();
            if (model.SchemeDetail == null)
                model.SchemeDetail = new List<Scheme_Mod>();
            return View(model);
        }
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Index_Post([Bind(Exclude="pageInfo")]DefaultModel model)
        {
            return Index(model);
        }
        private Key<string, object[]> getWhere(DefaultModel model)
        {
            var where = model.where;
            string sql=" 1==1 ";
            List<object>param=new List<object>();
            if (ActionName.Equals("History"))
            {
                sql += " and Issue.EndTime<@" + param.Count;
                param.Add(DateTime.Now);
            }
            else
            {
                sql += " and Issue.StartTime<=@" + param.Count + " and Issue.EndTime>=@" + param.Count;
                param.Add(DateTime.Now);
            }
            if(model.type==DefaultModel.Type.SelfOpenWin)
            {
                sql += string.Format(" and Issue.OpenCode !=@{3} and ( State=@{0} or State=@{1} or State=@{2} )", param.Count, param.Count + 1, param.Count + 2,param.Count+3);
                param.Add((short)SchemeState.Normal);
                param.Add((short)SchemeState.OutBill);
                param.Add((short)SchemeState.TimeOutCancel);
                param.Add(null);
            }
            
            if (where == null)
                return new Key<string, object[]>(sql, param.ToArray());
            else if (model.type == DefaultModel.Type.Normal)
            {
                if (where.State.HasValue && ActionName.Equals("History"))
                {
                    sql += " and State=@" + param.Count;
                    param.Add(where.State.Value);
                }
            }

            if (where.LotteryID.HasValue)
            {
                sql += " and Issue.LotteryID=@"+param.Count;
                param.Add(where.LotteryID.Value);
            }
            if (where.WinModelID.HasValue)
            {
                sql += " and WinModelID=@"+param.Count;
                param.Add(where.WinModelID.Value);
            }
            if (where.ConsumptionRatio.HasValue)
            {
                sql += " and ConsumptionRatio=@"+param.Count;
                param.Add(where.ConsumptionRatio.Value);
            }
            return new Key<string, object[]>(sql, param.ToArray());
        }
        #endregion

        #region 方案详情
        public ActionResult Detail(DetailModel model )
        {
            if (model==null||model.SchemeID==null)
                return RedirectToAction(ActionName);
            if (model.pageInfo == null)
            {
                model.pageInfo = new PageInfo();
                model.pageInfo.CurrPage = 1;
            }
            int sumCount;
            if (SM == null)
                SM = new SchemeManage();
            var data = SM.SchemeDetailList(model.SchemeID.Value, LoginUserID, (model.pageInfo.CurrPage - 1) * model.pageInfo.PageCount, model.pageInfo.PageCount, out sumCount).ToList();
            model.pageInfo.SunCount = sumCount;
            model.DetailList = data ;
            if(data==null||data.Count==0)
                return RedirectToAction(ActionName);
            if (ActionName.Equals("History"))
            {
                model.Scheme = SM.Select(s => s.Where(p => p.ID == model.SchemeID).ToArray().Select(p => new Scheme_Mod
                {
                    AddTime = p.AddTime,
                    IsChaseTask = p.IsChaseTask,
                    IssueNumber = p.Issue.FormatIssueName,
                    LotteryName = CacheManage.Lottery.Where(p1 => p1.Value.ID == p.Issue.LotteryID).Select(p1 => p1.Value.Name).FirstOrDefault(),
                    WinModelName = CacheManage.WinModel.Where(p1 => p1.Value.ID == p.WinModelID).Select(p1 => p1.Value.Name).FirstOrDefault(),
                    ConsumptionRatioName = CacheManage.Ratio.Where(p1 => p1.Value.Ratio == p.ConsumptionRatio).Select(p1 => p1.Value.Name).FirstOrDefault(),
                    SchemeCount = p.SchemeCount,
                    SchemeID = p.ID,
                    SchemeMoney = (double)p.SchemeMoney,
                    SchemeMultiple = p.Multiple,
                    SchemeOpenCode = p.Issue.OpenCode,
                    SchemeState = p.State,
                    SchemeWinMoney = (double?)p.WinMoney
                }).FirstOrDefault());
            }
            return View(model);
        }
        #endregion

        string ActionName ="Index";

        #region 历史记录
        public ActionResult History(DefaultModel model)
        {
            ActionName = "History";
            return Index(model);
        }
        [HttpPost]
        [ActionName("History")]
        public ActionResult History_Post([Bind(Exclude="pageInfo")]DefaultModel model)
        {
            ActionName = "History";
            return Index(model);
        }
        #endregion

        #region 历史方案详情
        public ActionResult HistoryDetail(DetailModel model)
        {
            ActionName = "History";
            if (SM == null)
                SM = new SchemeManage();
            if (model == null || model.SchemeID == null)
                return RedirectToAction(ActionName);
            var scheme = SM.Select(s => s.Where(p => p.ID == model.SchemeID).Select(p => new{p.ChaseTask_Detail,p.IsChaseTask }).FirstOrDefault());
            if (scheme != null && scheme.IsChaseTask)
                model.ChaseDetailList = new ChaseManage().ChaseTaskDetailList(LoginUserID, scheme.ChaseTask_Detail.ChaseTaskID);
            return Detail(model);
        }

        #endregion

        //撤单
        public JsonResult QuashOrder(Guid? ID)
        {
            var msg = string.Empty;
            var result = -1;
            if (ID.HasValue)
            {
                try
                {
                    result = new SchemeManage().CancleScheme(ID.Value, SchemeState.UserCancel, LoginUserID);

                    if (result > 0)
                    {
                        msg = "已成功撤单！";
                    }
                    else
                        msg = "操作失败,请稍后重新操作!";
                }
                catch (ValidateException e)
                {
                    msg = e.Message;
                }
                catch (AppException e1)
                {
                    msg = e1.Message;
                }
                catch (Exception e2)
                {
                    msg = "操作失败,请稍后重新操作!";
                    if (Log.IsDebugEnabled)
                        Log.Debug("撤消方案失败！ID:"+ID.Value, e2);
                    if (Log.IsWarnEnabled)
                        Log.Warn("撤消方案失败！ID:"+ID.Value);
                }
            }
            return Json(new {msg,result},JsonRequestBehavior.AllowGet);
        }

        //自助补奖
        public JsonResult SelfOpenWin(Guid? id)
        {
            var count = -1;
            var state = string.Empty;
            var msg = string.Empty;
            decimal? money = 0;
            if (id.HasValue)
            {
                try
                {
                    var sm = new SchemeManage();
                    count = sm.BuJian(id.Value);
                    var scheme = sm.Select(s => s.Where(p => p.ID == id.Value).FirstOrDefault());
                    var schemeState = (SchemeState)scheme.State;
                    money = scheme.WinMoney;
                    state = schemeState.GetName();
                    if (money.HasValue && money > 0)
                    {
                        msg = "恭喜您中奖!";
                    }
                    else if (count >= 0)
                    {
                        msg = "补奖成功！";
                    }
                    else
                    {
                        msg = "操作失败,请稍后重新操作!";
                    }
                    if (money==null||money < 0)
                        money = 0;
                }
                catch (ValidateException e)
                {
                    msg = e.Message;
                }
                catch (AppException e1)
                {
                    msg = e1.Message;
                }
                catch (Exception e2)
                {
                    msg = "操作失败,请稍后重新操作!";
                    if (Log.IsDebugEnabled)
                        Log.Debug("自助补奖操作失败，id:"+id.Value,e2);
                    if (Log.IsWarnEnabled)
                        Log.Warn("自助补奖操作失败，id:" + id.Value);
                }
            }
            return Json(new {state,count,msg,winMoney=money },JsonRequestBehavior.AllowGet);
        }

    }
}
